//! 简化的消息总线核心功能测试

use rustcloud_bus::{
    bus::MessageBus,
    memory::InMemoryMessageBus,
    message::Message,
    error::MessageBusResult,
    event::{Event, EventType, EventContext, EventBus},
    event_bus::MessageBusEventBus,
};
use serde_json::json;
use std::sync::Arc;
use tokio::time::timeout;
use std::time::Duration;

/// 测试消息总线基本功能
#[tokio::test]
async fn test_message_bus_basic_operations() -> MessageBusResult<()> {
    let bus = InMemoryMessageBus::new().await?;

    // 测试发布消息
    let message = Message::new("test.topic", json!({"data": "test"}));
    bus.publish(message).await?;

    // 测试统计信息
    let stats = bus.stats().await?;
    assert_eq!(stats.total_published, 1);

    // 测试关闭
    bus.close().await?;
    Ok(())
}

/// 测试发布订阅模式
#[tokio::test]
async fn test_publish_subscribe_pattern() -> MessageBusResult<()> {
    let bus = InMemoryMessageBus::new().await?;

    // 创建订阅者
    let subscriber = bus.subscribe("test.events.*").await?;

    // 发布匹配消息
    let message1 = Message::new("test.events.created", json!({"id": 1}));
    bus.publish(message1).await?;

    // 接收消息
    let received = subscriber.receive_timeout(1000).await?;
    assert!(received.is_some());
    
    let msg = received.unwrap();
    assert_eq!(msg.topic(), "test.events.created");
    assert_eq!(msg.payload()["id"], 1);

    Ok(())
}

/// 测试事件总线
#[tokio::test]
async fn test_event_bus() -> MessageBusResult<()> {
    let message_bus = Arc::new(InMemoryMessageBus::new().await?);
    let event_bus = MessageBusEventBus::new(message_bus).await?;

    // 创建事件
    let context = EventContext::new("test-service".to_string())
        .with_user_id("user123".to_string());
    
    let event = Event::new(
        "user.registered".to_string(),
        EventType::Domain,
        json!({"user_id": "user123", "email": "test@example.com"}),
        context,
    );

    // 发布事件
    let result = event_bus.publish_event(event).await;
    assert!(result.is_ok());
    
    Ok(())
}

/// 测试并发安全性
#[tokio::test]
async fn test_concurrent_operations() -> MessageBusResult<()> {
    let bus = Arc::new(InMemoryMessageBus::new().await?);
    
    // 创建多个并发任务
    let mut tasks = Vec::new();
    
    for i in 0..10 {
        let bus_clone = bus.clone();
        let task = tokio::spawn(async move {
            for j in 0..10 {
                let message = Message::new(
                    &format!("concurrent.test.{}.{}", i, j),
                    json!({"thread": i, "message": j})
                );
                let _ = bus_clone.publish(message).await;
            }
        });
        tasks.push(task);
    }
    
    // 等待所有任务完成
    for task in tasks {
        task.await.unwrap();
    }
    
    // 验证统计信息
    let stats = bus.stats().await?;
    assert_eq!(stats.total_published, 100);
    
    Ok(())
}

/// 运行所有测试
pub async fn run_all_tests() -> MessageBusResult<()> {
    println!("🧪 开始运行消息总线简化测试...\n");
    
    let mut passed = 0;
    let mut failed = 0;
    
    // 测试基本操作
    print!("  • 测试消息总线基本操作: ");
    match timeout(Duration::from_secs(10), test_message_bus_basic_operations()).await {
        Ok(Ok(())) => {
            println!("✅ 通过");
            passed += 1;
        }
        Ok(Err(e)) => {
            println!("❌ 失败 - {:?}", e);
            failed += 1;
        }
        Err(_) => {
            println!("⏱️ 超时");
            failed += 1;
        }
    }
    
    // 测试发布订阅
    print!("  • 测试发布订阅模式: ");
    match timeout(Duration::from_secs(10), test_publish_subscribe_pattern()).await {
        Ok(Ok(())) => {
            println!("✅ 通过");
            passed += 1;
        }
        Ok(Err(e)) => {
            println!("❌ 失败 - {:?}", e);
            failed += 1;
        }
        Err(_) => {
            println!("⏱️ 超时");
            failed += 1;
        }
    }
    
    // 测试事件总线
    print!("  • 测试事件总线: ");
    match timeout(Duration::from_secs(10), test_event_bus()).await {
        Ok(Ok(())) => {
            println!("✅ 通过");
            passed += 1;
        }
        Ok(Err(e)) => {
            println!("❌ 失败 - {:?}", e);
            failed += 1;
        }
        Err(_) => {
            println!("⏱️ 超时");
            failed += 1;
        }
    }
    
    // 测试并发操作
    print!("  • 测试并发操作: ");
    match timeout(Duration::from_secs(10), test_concurrent_operations()).await {
        Ok(Ok(())) => {
            println!("✅ 通过");
            passed += 1;
        }
        Ok(Err(e)) => {
            println!("❌ 失败 - {:?}", e);
            failed += 1;
        }
        Err(_) => {
            println!("⏱️ 超时");
            failed += 1;
        }
    }
    
    println!("\n📊 测试结果统计:");
    println!("  • 通过: {} 个", passed);
    println!("  • 失败: {} 个", failed);
    println!("  • 总计: {} 个", passed + failed);
    
    if failed == 0 {
        println!("\n🎉 所有测试通过！");
        Ok(())
    } else {
        Err(rustcloud_bus::error::MessageBusError::internal_error(
            format!("测试失败: {} 个", failed)
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn run_test_suite() {
        run_all_tests().await.unwrap();
    }
}